#include <iostream>
#include <ctime>
#include <cassert>
#include <unistd.h>
#include "Socket.hpp"
#include "Protocol.hpp"

void Usage(char* proc)
{
    std::cout << "Usage:" << proc << "serverip serverport" << std::endl;
}
int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    uint16_t serverport = std::stoi(argv[2]);
    std::string serverip = argv[1];

    Socket socket;
    socket.Initsocket();

    char buffer[1024];

    memset(buffer, 0, sizeof(buffer));
    int r = socket.Connect(serverip, serverport);
    if (!r) return 1;

    srand(time(nullptr));
    int cnt = 1;
    const std::string oper = "+-*/%=";
    std::string inffer_stream;
    while (cnt <= 20)
    {
        // 写
        int x = rand() % 100 + 1;
        usleep(1234);
        int y = rand() % 100;
        usleep(4321);
        char op = oper[rand() % oper.size()];

        Request req(x, y, op);
        req.DebugPrint(); // 打印任务内容
        std::string package;
        // 系序列化
        req.Serialization(&package);
        // 加报头
        package = Encode(package);

        write(socket.getSockfd(), package.c_str(), package.size());

        // -----------------------------------------------------------------

        // 读
        char buffer[1024];
        ssize_t n = read(socket.getSockfd(), buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            inffer_stream += buffer;
            std::cout << inffer_stream << std::endl;

            // 去报头
            std::string content;
            bool r = Decode(inffer_stream, &content);
            assert(r);
            // 反序列化
            Respond res;
            r = res.Deserialization(content);
            assert(r);

            res.DubugPrint();
        }

        std::cout << "=============================================" << std::endl;
        cnt++;
        sleep(1);
    }

    close(socket.getSockfd());

    return 0;
}